package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDTO;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/18 15:56
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    CourseBaseMapper courseBaseMapper;
    
    @Resource
    CourseMarketMapper courseMarketMapper;
    
    @Resource
    CourseCategoryMapper courseCategoryMapper;

    /**
     * 课程分页查询
     * @param companyId 机构id
     * @param pageParams 分页查询参数
     * @param courseParamsDTO 查询条件
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDTO courseParamsDTO) {
        // 查询条件
        // 拼接查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 根据名称模糊查询, 在sql中拼接course_name like "%#{courseName}%"
        queryWrapper.like(StringUtils.isNotEmpty(courseParamsDTO.getCourseName()), CourseBase::getName, courseParamsDTO.getCourseName());
        // 根据课程审核状态查询 course_base.audit_status = ?
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDTO.getAuditStatus()), CourseBase::getAuditStatus, courseParamsDTO.getAuditStatus());
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDTO.getPublishStatus()), CourseBase::getStatus, courseParamsDTO.getPublishStatus());
        // 根据培训机构id拼接查询条件
        queryWrapper.eq(CourseBase::getCompanyId, companyId);

        // 创建Page分页参数对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        List<CourseBase> items = pageResult.getRecords();
        long total = pageResult.getTotal();

        PageResult<CourseBase> result = new PageResult<>(items, total, pageParams.getPageNo(), pageParams.getPageSize());
        return result;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        
        // 参数的合法性校验
        //合法性校验
        /*if (StringUtils.isBlank(dto.getName())) {
            //throw new RuntimeException("课程名称为空");
            XueChengPlusException.cast("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }*/
        
        // 向课程基本信息表course_base写入数据
        CourseBase courseBase = new CourseBase();
        // 将传入页面的参数放到courseBase对象
        //courseBase.setName(dto.getName());
        //courseBase.setDescription(dto.getDescription());
        // 步骤复杂
        BeanUtils.copyProperties(dto, courseBase); // 只要属性名称一致就可以拷贝，如果被拷贝对象属性为空，拷贝对象的对应属性也会为空
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        // 审核状态默认为未提交
        courseBase.setAuditStatus("202002");
        // 发布状态为未发布
        courseBase.setStatus("203001");
        // 插入数据库
        int insert = courseBaseMapper.insert(courseBase);
        System.out.println("insert = " + insert);
        if (insert <= 0){
            throw new RuntimeException("添加课程失败");
        }

        // 向课程营销 course_market写数据
        CourseMarket courseMarket = new CourseMarket();
        // 将页面输入的数据拷贝到courseMarket中
        BeanUtils.copyProperties(dto, courseMarket);
        // 主键课程的id
        courseMarket.setId(courseBase.getId());
        // 保存营销信息
        saveCourseMarket(courseMarket);
        // 从数据库查询出课程的详细信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseBase.getId());

        return courseBaseInfo;
    }


    /**
     * 根据课程id查询课程信息
     * @param courseId 课程id
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        // 从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            return null;
        }

        // 从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket == null){
            return null;
        }
        
        // 组装在一起
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null){
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        // 课程分类的名称:
        // 大分类
        CourseCategory mtObj = courseCategoryMapper.selectById(courseBase.getMt());
        String mtName = mtObj.getName();
        courseBaseInfoDto.setMtName(mtName);
        // 小分类
        CourseCategory stObj = courseCategoryMapper.selectById(courseBase.getSt());
        String stName = stObj.getName();
        courseBaseInfoDto.setStName(stName);
        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCoursesBase(Long companyId, EditCourseDto editCourseDto) {
        
        // 拿到课程id
        Long courseId = editCourseDto.getId();
        // 根据课程id得到课程的机构id
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        if (courseBaseInfo == null){
            XueChengPlusException.cast("课程不存在");
        }

        // 数据合法性校验
        // 根据具体的业务逻辑去校验
        // 本机构只能修改本机构的课程
        if (!companyId.equals(courseBaseInfo.getCompanyId())){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }
        
        // 封装基本信息的数据
        BeanUtils.copyProperties(editCourseDto, courseBaseInfo);
        courseBaseInfo.setChangeDate(LocalDateTime.now());
        
        // 更新课程基本信息
        int res = courseBaseMapper.updateById(courseBaseInfo);
        if (res <= 0){
            XueChengPlusException.cast("修改课程失败");
        }

        // 封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        saveCourseMarket(courseMarket);
        
        // 查询课程信息
        CourseBaseInfoDto courseBase = this.getCourseBaseInfo(courseId);
        return courseBase;
    }

    // 存在则更新 不存在就添加
    //保存课程营销信息
    private int saveCourseMarket(CourseMarket courseMarketNew){
        //收费规则
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new RuntimeException("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue()<=0){
                //throw new RuntimeException("课程为收费价格不能为空且必须大于0");
                XueChengPlusException.cast("课程为收费价格不能为空且必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarketNew.getId());
        if(courseMarketObj == null){
            return courseMarketMapper.insert(courseMarketNew);
        }else{
            BeanUtils.copyProperties(courseMarketNew,courseMarketObj);
            courseMarketObj.setId(courseMarketNew.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }
}
